<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/2
 * Time: 14:20
 */

namespace Shop\Api;


use Common\Api\Api;
use Shop\Model\WalletModel;
use Shop\Model\WalletApplyModel;
use Shop\Api\WalletApplyApi;
use Shop\Api\WalletHisApi;

class WalletApi extends Api{
    /*public*/
    const GET_INFO = "Shop/Wallet/getInfo";
	const SAVE_BY_ID = "Shop/Wallet/saveByID";
    /*private*/
    const GET_INFO_If_NOT_EXIST_THEN_ADD = "Shop/Wallet/getInfoIfNotExistThenAdd";
    const PLUS = "Shop/Wallet/plus";
    const MINUS = "Shop/Wallet/minus";



    protected function _init(){
        $this->model = new WalletModel();
    }

    /**
     * 有钱包则返回钱包，没有则添一个
     * @author 老胖子-何必都 <hebiduhebi@126.com>
     * @param $uid
     * @return array|\Model|\Think\Model
     */
	public function getInfoIfNotExistThenAdd($uid){
		//UID
		$map = array(
			'uid'=>$uid,
		);

		$wallet = $this->model->where($map)->find();
        if($wallet === false){
            return $this->apiReturnErr("查找钱包失败!");
        }
		if(empty($wallet)){
			$wallet=M('Wallet');
			$time=time();
			$entity=array(
				'uid'=>$uid,
				'frozen_funds'=>0,
				'account_balance'=>0,
				'update_time'=>$time,
			);
			$w = $wallet->add($entity);
            if($w === false){
                return $this->apiReturnErr("添加钱包失败!");
            }
			$entity=array(
				'id'=>$w,
				'uid'=>$uid,
				'frozen_funds'=>0,
				'account_balance'=>0,
				'update_time'=>$time,
			);

			return $this->apiReturnSuc($entity);
		}

        return $this->apiReturnSuc($wallet);
	}

    /**
     *    加佣金
     * @param $uid  int 用户ID
     * @param $money  float 钱
     * @param $type  string 增加类型
     * @param $reason string 原因
     * @return 返回影响记录数 int
     */
	public function plus($uid,$money,$type,$reason){
        $trans = M();
        $trans->startTrans(); //开启事务
        $result = apiCall(WalletApi::GET_INFO_If_NOT_EXIST_THEN_ADD,array($uid));
        $error = false;
        if($result === false){
            $error = $this->model->getDbError();
        }

        if(empty($result)){
            $error = "钱包信息为空!";
        }
        $id = $result['info']['id'];
        $beforeMoney = $result['info']['account_balance'];
        $afterMoney = $beforeMoney + $money;
        if($error === false){
            $entity=array(
                'uid'=>$uid,
                'before_money'=>$beforeMoney,
                'plus'=>$money,
                'minus'=>0,
                'after_money'=>$afterMoney,
                'create_time'=>time(),
                'dtree_type'=>$type,
                'reason'=>$reason,
            );

            $result=apiCall(WalletHisApi::ADD,array($entity));

            if($result['status'] === false){

                $error = $result['info'];

            }else{
                $result = apiCall(WalletApi::SAVE_BY_ID,array($id,array('account_balance'=>$afterMoney)));

                if($result['status'] === false){
                    $error = $result['info'];
                }
            }
        }

        if($error === false){
            $trans->commit();
            return $this->apiReturnSuc($result);
        }else{
            $trans->rollback();
            return $this->apiReturnErr($error);
        }

    }


    /**
     * 减账户余额 - 并记录 - 调用时需要外部添加事务
     * money : 减少的数额 >0
     * @author : rainbow
     */
    public function minus($uid=0,$money=0,$type=0,$note=''){
        //check wallet
        if(floatval($money)<=0) return  $this->apiReturnErr('参数错误');
        $r = $this->model->where(array('uid'=>$uid))->find();
        if(false === $r) return $this->apiReturnErr($this->model->getDbError());
        if(empty($r)) return $this->apiReturnErr('余额不足:NULL');
        if(1 === intval($r['wallet_type'])) return $this->apiReturnErr('用户余额账户冻结中');
        $all_money = floatval($r['account_balance']);
        $after_money = $all_money - floatval($r['frozen_funds']);
        if($after_money < $money) return $this->apiReturnErr('余额不足');
        //dec wallet
        //已检查过
        $r = $this->setDec(array('uid'=>$uid),'account_balance',$money);
        if(!$r['status']) return $this->apiReturnErr($r['info']);
        //log wallet_his
        $map = array(
            'uid'          =>$uid,
            'before_money' =>$all_money,
            'plus'         =>0,
            'minus'        =>$money,
            'after_money'  =>$after_money,
            'create_time'  =>time(),
            'dtree_type'   =>$type,
            'reason'       =>$note,
            'wallet_type'  =>0,
            // 'result'       =>1
        );
        $r = apiCall(WalletHisApi::ADD,array($map));
        if(!$r['status']) return $this->apiReturnErr($r['info']);
        return $this->apiReturnSuc('操作成功');
    }
}